﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DbLib;
using DbLib.models;
using System.Diagnostics;
using System.Reflection;

namespace BLL
{
    public class BaseBll
    {
        public virtual bool Add<T>(T obj) where T : class
        {
            return LinqHelper.Add(obj);
        }

        public virtual bool Update<T>(T obj, List<string> changeField) where T : class
        {
            return LinqHelper.Update(obj, changeField);
        }

        public virtual bool Remove<T>(T obj) where T : class
        {
            return LinqHelper.Remove(obj);
        }

        public virtual List<T> GetList<T>(T obj) where T : class
        {
            List<Conditioner> condition = GetFilter(obj);
            try
            {
                using (order02Context db = new order02Context())
                {
                    var query = db.Set<T>().AsQueryable();
                    List<T> list = LinqHelperExtension.Where(query, condition.ToArray()).ToList();
                    return list;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(DateTime.Now + ex.Message + "\n\r");
                throw ex;
            }
        }

        public virtual List<T> GetList<T>(T obj, int pageSize, int pageNum, ref int totalRecord) where T : class
        {
            List<Conditioner> condition = GetFilter(obj);

            try
            {
                using (order02Context db = new order02Context())
                {
                    var query = db.Set<T>().AsQueryable();

                    List<T> list = LinqHelperExtension.Where(query, condition.ToArray()).ToList();
                    totalRecord = list.Count;
                    return list.Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(DateTime.Now + ex.Message + "\n\r");
                throw ex;
            }
        }

        private List<Conditioner> GetFilter<T>(T obj) where T : class
        {
            Type t = obj.GetType();
            List<Conditioner> condition = new List<Conditioner>();
            PropertyInfo[] propertis = t.GetProperties();
            for (int i = 0; i < propertis.Length; i++)
            {
                if (!Equals(propertis[i].GetValue(obj, null), null))
                {
                    condition.Add(new Conditioner { Key = propertis[i].Name, Value = propertis[i].GetValue(obj, null).ToString(), Contract = "=" });
                }
            }
            return condition;
        }
    }
}
